define(function (require, exports, module) {
    var $ = require('jquery');
    var _ = require('underscore');
    var AjaxManager = require('./ajaxManager').AjaxManager;
    var Mustache = require('Mustache');
    var Modal = require('./modal').Modal;

    function Plans () {
        var that = this;

        this.$container = $('#recharge-plans');

        this.modal = null;

        this.$customPlan =  $('#plan-custom');

        this.$customPlanInput = this.$customPlan.find('input');

        this.$customPlanInput
            .change(function (ev) {
                var number = ev.target.value * 1;

                if (!_.isNumber(number)) {
                    number = 0;
                    ev.target.value = number;
                }

                that.compute(number);

            })
            .keyup(function (ev) {
                var target = ev.target;
                var value = target.value.replace(/[^0-9]/g, '');

                if (value != target.value) {
                    target.value = value;
                }

                that.computeTimeout = setTimeout(function () {
                    that.compute(target.value * 1);
                }, 300);
            })
            .keydown(function (ev) {
                clearTimeout(that.computeTimeout);

                if (ev.keyCode < 48 && ev.keyCode > 57) {
                    ev.preventDefault();
                }
            });

        this.compute(this.$customPlanInput.val() * 1);

        this.payModal = null;

        this.$container.delegate('.plan-btn', 'click', function (ev) {
            ev.preventDefault();

            if (!that.payModal) {
                that.payModal = new Modal('#pay-modal');
                that.payModal.container
                    .delegate('.link', 'click', function (ev) {
                        ev.preventDefault();

                        that.payModal.hide();
                    })
                    .delegate('.btn', 'click', function () {
                        window.location.reload();
                    });
            }

            that.payModal.show();
        });

        this.computeTimeout = null;

    }

    Plans.prototype.compute = function (number) {
        var $price = this.$customPlan.find('.plan-price .figure');
        var $unitprice = this.$customPlan.find('.plan-unitprice .figure');
        var unitprice = 0;


        if (number > 0 && number <= 500) {
            unitprice = 0.07;
        } else if (number > 500 && number <= 1000) {
            unitprice = 0.068;
        } else if (number > 1000 && number <= 5000) {
            unitprice = 0.065;
        } else if (number > 5000) {
            unitprice = 0.06;
        }

        $unitprice.html(unitprice);

        $price.html((unitprice * number).toFixed(2));
    };

    Plans.prototype.recharge = function () {
        // todo
    };

    exports.Plans = Plans;
});